package us.icitap.cm.ui.policecase;

import java.util.Arrays;
import java.util.List;

import us.icitap.cm.CaseManagementUI;
import us.icitap.cm.business.AppListTypeEnum;
import us.icitap.cm.business.entities.AppEntity;
import us.icitap.cm.business.entities.AppList;
import us.icitap.cm.business.entities.Drug;
import us.icitap.cm.business.entities.EntityTypeEnum;
import us.icitap.cm.business.entities.Evidence;
import us.icitap.cm.business.entities.Evidence.EvidenceTypeEnum;
import us.icitap.cm.business.entities.UnitEnum;
import us.icitap.cm.business.entities.regmin.States;
import us.icitap.cm.listeners.AppEntityListener;
import us.icitap.cm.ui.custom.CustBeanFieldGroup;
import us.icitap.cm.ui.custom.CustComboBox;
import us.icitap.cm.ui.custom.CustTextArea;
import us.icitap.cm.ui.custom.CustTextField;
import us.icitap.cm.ui.custom.CustomFormLayout;
import us.icitap.cm.ui.shared.AppEntityLayout;
import us.icitap.cm.utils.ProjectLists;
import us.icitap.utils.Result;

import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.ui.AbstractSelect.ItemCaptionMode;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.TabSheet;
import com.vaadin.ui.VerticalLayout;

public class DrugDataLayout extends AppEntityLayout{

	/**
	 * 
	 */
	private static final long serialVersionUID = 4116310929664965957L;

	private Drug drug;
	private final CustBeanFieldGroup<Drug> binder = new CustBeanFieldGroup<Drug>(Drug.class);
	
	final CustComboBox drugClassificationSelect = new CustComboBox("Klasifikimi");
	final CustComboBox drugTypeSelect = new CustComboBox("Lloji i droges");
	final CustTextField quantityTextField = new CustTextField("Sasia");
	final CustComboBox unitSelect = new CustComboBox("Njesia matese");
	final CustComboBox orginCountrySelect = new CustComboBox("Vendi i origjines");
	final CustComboBox destinationCountrySelect = new CustComboBox("Destinacioni");
	final CustComboBox transitCountrySelect = new CustComboBox("Vendi transit");
	final CustTextArea notesTextArea = new CustTextArea();

	private final CheckBox evidenceCheckBox = new CheckBox("Eshte prove materiale");
	
	protected AppEntityListener listener;
	final CustomFormLayout cfl = new CustomFormLayout("450px", "Droga/Narkotike te perfshire ne ngjarje", "Reset", "Ruaj");
	
	boolean editableVisible = false;
	boolean readOnlyVisible = false;
	
	private final EvidenceEmbeddableDataLayout evidenceEmbDataLayout = new EvidenceEmbeddableDataLayout();
	final TabSheet tabSheet = new TabSheet();
	
	public DrugDataLayout() {
		this.setMargin(true);
		
		
		FormLayout fl = new FormLayout();
		fl.addStyleName("cmLayout");
		fl.setMargin(true);
		
		fl.addComponent(this.drugClassificationSelect);
		fl.addComponent(this.drugTypeSelect);
		fl.addComponent(this.quantityTextField);
		fl.addComponent(this.unitSelect);
		fl.addComponent(this.orginCountrySelect);
		fl.addComponent(this.destinationCountrySelect);
		fl.addComponent(this.transitCountrySelect);
		fl.addComponent(this.notesTextArea);
		fl.addComponent(this.evidenceCheckBox);
		
		this.quantityTextField.setWidth("6em");
		this.unitSelect.setWidth("8em");
		this.notesTextArea.setWidth("20em");
		tabSheet.addTab(fl, "Te dhenat");
		
		
		cfl.addComponent(tabSheet);
		cfl.addFooter();
		
		drugClassificationSelect.setContainerDataSource(new BeanItemContainer<AppList>(AppList.class, ProjectLists.getList(AppListTypeEnum.DrugClassification, false)));
		drugClassificationSelect.setImmediate(true);
		
			
		unitSelect.setContainerDataSource(new BeanItemContainer<UnitEnum>(UnitEnum.class, Arrays.asList(UnitEnum.values())));
		
		transitCountrySelect.setContainerDataSource(new BeanItemContainer<States>(States.class, ProjectLists.getStatesList(false)));
	
		
		
		destinationCountrySelect.setContainerDataSource(new BeanItemContainer<States>(States.class, ProjectLists.getStatesList(false)));
		destinationCountrySelect.setItemCaptionMode(ItemCaptionMode.EXPLICIT);
		destinationCountrySelect.setItemCaptionPropertyId("tag");
		
		orginCountrySelect.setContainerDataSource(new BeanItemContainer<States>(States.class, ProjectLists.getStatesList(false)));
		orginCountrySelect.setItemCaptionMode(ItemCaptionMode.EXPLICIT);
		orginCountrySelect.setItemCaptionPropertyId("tag");
		
		cfl.addRightClickListener(new ClickListener() {
			
			@Override
			public void buttonClick(ClickEvent event) {
				try {
					binder.commit();
					if(DrugDataLayout.this.listener != null){
						if(oldAppEntity == null){
							// Eshte entitet i ri
							if((evidenceCheckBox.getValue().booleanValue())){
								drug.getAppEntity().setEvidence(evidenceEmbDataLayout.getEvidence());	
							}
							DrugDataLayout.this.listener.addAppEntityToReport(drug.getAppEntity());
						}
						else{
							//Eshte entitet ekzistues
							System.out.println("Eshte entitet ekzistues");
							drug.getAppEntity().setEvidence(evidenceEmbDataLayout.getEvidence());
							if(!oldAppEntity.getDrug().myEquals(drug)){
								System.out.println("Entiteti ka ndryshuar");
								if(drug.getAppEntity().getEvidence() != null && 
										drug.getAppEntity().getEvidence().myEquals(oldAppEntity.getEvidence())){
									System.out.println("Nuk ka ndryshuar prova");
									drug.getAppEntity().setEvidence(oldAppEntity.getEvidence());
								}
								
								drug.getAppEntity().setRecordUser(CaseManagementUI.getUser().getUsername());
								DrugDataLayout.this.listener.updateAppEntityIntoReport(oldAppEntity, drug.getAppEntity());
							}
							else
							{
								System.out.println("Entiteti nuk k ndryshuar, as prova");
//								oldAppEntity.replaceEntityReportAssociationList(drug.getAppEntity().getReportAssociationList());
								DrugDataLayout.this.listener.refresh(oldAppEntity);
							}
							
							addAppEntity();
						}
							
						
					
					}	
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		
		binder.bind(drugClassificationSelect, "drugClassification");
		binder.bind(drugTypeSelect, "drugType");
		binder.bind(unitSelect, "unit");
		binder.bind(quantityTextField, "quantity");
		binder.bind(orginCountrySelect, "originCountry");
		binder.bind(destinationCountrySelect, "destinationCountry");
		binder.bind(transitCountrySelect, "transitCountry");
		binder.bind(notesTextArea, "notes");
		
		evidenceCheckBox.setImmediate(true);
		evidenceCheckBox.addValueChangeListener(new ValueChangeListener() {
			
			@Override
			public void valueChange(ValueChangeEvent event) {
				if(evidenceCheckBox.getValue().booleanValue()){
					// Entiti shoqerohet me prove
					tabSheet.addTab(evidenceEmbDataLayout, "Prove materiale");
					
					if(oldAppEntity != null && oldAppEntity.getEvidence() != null){
						// Entiteti ekzistues ka prove ekzistuese te lidhur me te
						drug.getAppEntity().setEvidence(new Evidence(oldAppEntity.getEvidence()));
						evidenceEmbDataLayout.loadEvidence(drug.getAppEntity().getEvidence(),true);
					}
					else{
						// Entiteti ekzistues nuk ka prove ekzistues te lidhur me te
						// Krijohet prove e re 
						evidenceEmbDataLayout.createEvidence(EvidenceTypeEnum.MATERIAL);
					}
				}
				else{
					// Entiteti nuk ka prove ekzistuese te lidhur me te
					drug.getAppEntity().setEvidence(null);
					tabSheet.removeComponent(evidenceEmbDataLayout);
					
				}
					
				
				
			}
		});
		

		
		drugClassificationSelect.addValueChangeListener(new ValueChangeListener() {
			
			@Override
			public void valueChange(ValueChangeEvent event) {
				drugTypeSelect.removeAllItems();
				if(drugClassificationSelect.getValue() != null){
					AppList parent = (AppList) drugClassificationSelect.getValue();
					Result<List<AppList>> result = CaseManagementUI.appStatelessBean.getPersistenceBean().getAppListChildren(parent);
					if(result.isSucceeded() && result.getObject() != null && !result.getObject().isEmpty()){
						drugTypeSelect.setContainerDataSource(new BeanItemContainer<AppList>(AppList.class, result.getObject()));
						
					}
				}
				
				
			}
		});
		
	}
	
	public void showEditableForm(){
		if(editableVisible) return ;
		
		this.removeAllComponents();
		this.addComponent(cfl);
		
		editableVisible = true;
		readOnlyVisible = false;
	}
	

	public void showReadOnlyForm(){
		if(readOnlyVisible) return;
		this.removeAllComponents();
		VerticalLayout vl = ViewCaseLayout.showDrug(drug);
		vl.setCaption(EntityTypeEnum.DRUG.getCaption());
		this.addComponent(vl);
		editableVisible = false;
		readOnlyVisible = true;
	}
	

	@Override
	public void addAppEntity() {
		this.tabSheet.setSelectedTab(0);
		AppEntity appEntity = new AppEntity(CaseManagementUI.getUser().getUsername(), EntityTypeEnum.DRUG);
		drug = appEntity.getDrug();

		binder.setItemDataSource(drug);
		this.showEditableForm();

	}


	@Override
	public void addAppEntityListener(AppEntityListener listener) {
		this.listener = listener;
		
	}

	private AppEntity oldAppEntity;
	
	@Override
	public void loadAppEntity(AppEntity appEntity, boolean editable) {

		oldAppEntity = appEntity;
		
		AppEntity newAppEntity = new AppEntity(appEntity);
		
		this.drug = newAppEntity.getDrug();
		binder.setItemDataSource(drug);
		
		if(newAppEntity.getEvidence()!= null){
			evidenceCheckBox.setValue(new Boolean(true));
			evidenceEmbDataLayout.loadEvidence(newAppEntity.getEvidence(), true);
			tabSheet.addTab(evidenceEmbDataLayout, "Prove materiale");
		}
		else{
			evidenceCheckBox.setValue(new Boolean(false));
		}
		
		if(editable) 
			this.showEditableForm();
		
		else
			this.showReadOnlyForm();
	}

	


}
